package uk.co.mmscomputing.device.sane.applet;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.applet.Applet;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

import java.awt.image.BufferedImage;

import sun.misc.BASE64Encoder;
import uk.co.mmscomputing.device.scanner.Scanner;
import uk.co.mmscomputing.device.scanner.ScannerDevice;
import uk.co.mmscomputing.device.scanner.ScannerListener;
import uk.co.mmscomputing.device.scanner.ScannerIOMetadata;
import uk.co.mmscomputing.device.scanner.ScannerIOException;
import uk.co.mmscomputing.imageio.jpeg.JPEGImageWriterSpi;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;

import netscape.javascript.JSObject;

public class SaneAppletExample extends Applet implements ActionListener,
		ScannerListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public String filename;

	Scanner scanner;
	JButton acquireButton, selectButton, cancelButton;

	public SaneAppletExample() {
	}

	public SaneAppletExample(String title, String[] argv) {
		JFrame.setDefaultLookAndFeelDecorated(true);

		JFrame frame = new JFrame(title);
		// frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

		frame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent ev) {
				stop();
				System.exit(0);
			}
		});

		init();

		frame.getContentPane().add(this);
		frame.pack();
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);
		start();
	}

	public void init() {
		setLayout(new BorderLayout());
		selectButton = new JButton("select");
//		 add(selectButton);
		selectButton.addActionListener(this);
		this.setSize(160, 45);
		acquireButton = new JButton();
		acquireButton.setBorder(BorderFactory.createEmptyBorder());
		acquireButton.setContentAreaFilled(false);
		add(acquireButton);
		acquireButton.setBounds(0,0,160,45);
		try {
			acquireButton
					.setIcon(new ImageIcon(
							Toolkit.getDefaultToolkit()
									.getImage(
											getClass()
													.getResource(
															"/uk/co/mmscomputing/device/sane/applet/escanear.png"))));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// acquireButton.setOpaque(false);
		// acquireButton.setContentAreaFilled(false);
		// acquireButton.setBorderPainted(false);
		// acquireButton.setBorder(null);
		acquireButton.addActionListener(this);

		cancelButton = new JButton("cancel next scan");
		// add(cancelButton);
		cancelButton.addActionListener(this);

		// filename=System.getProperty("user.home")+"/test.tiff";
		String name = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		filename = "c://images//" + name + ".jpg";

		scanner = Scanner.getDevice();
		scanner.addListener(this);
	}

	public void actionPerformed(ActionEvent evt) {
		try {
			if (evt.getSource() == acquireButton) {
				scanner.acquire();
			} else if (evt.getSource() == selectButton) {
				scanner.select();
			} else if (evt.getSource() == cancelButton) {
				scanner.setCancel(true);
			}
		} catch (ScannerIOException sioe) {
			sioe.printStackTrace();
		}
	}

	public void update(ScannerIOMetadata.Type type, ScannerIOMetadata metadata) {

		if (type.equals(ScannerIOMetadata.ACQUIRED)) {
			BufferedImage image = metadata.getImage();
			System.out.println("Have an image now!");
			try {
//				File file = new File(filename);
//				System.out.println("Image Path: " + file.getAbsolutePath());
//				 TIFFImageWriterSpi tiw = new TIFFImageWriterSpi();
//				 JPEGImageWriterSpi tiw = new JPEGImageWriterSpi();
//				 ImageWriter imageWriter = tiw.createWriterInstance();
//				 ImageOutputStream ios = ImageIO.createImageOutputStream
//				 (file);
//				 imageWriter.setOutput(ios);
//				 imageWriter.write(image);
//				 ios.flush();
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				ImageIO.write(image, "jpg", bos);
				byte[] imageBytes = bos.toByteArray();
				BASE64Encoder encoder = new BASE64Encoder();
	            String imageString = encoder.encode(imageBytes);
	            filename = "data:image/jpeg;base64,"+imageString;
	            JSObject window = JSObject.getWindow(this);
	            window.eval("enterNums()");
//	            System.out.println(filename);
//				ImageIO.write(image, "jpg", file);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (type.equals(ScannerIOMetadata.NEGOTIATE)) {
			ScannerDevice device = metadata.getDevice();

			try {
//				device.setShowUserInterface(true);
				
//				device.setRegionOfInterest(30,30,3000,3000);
				device.setResolution(300.0);
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else if (type.equals(ScannerIOMetadata.STATECHANGE)) {
			System.err.println(metadata.getStateStr());
		} else if (type.equals(ScannerIOMetadata.EXCEPTION)) {
			metadata.getException().printStackTrace();
		}
	}

	public static void main(String[] argv) {
		try {
			SaneAppletExample app = new SaneAppletExample(
					"Sane Applet Example [2007-11-19]", argv);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}